package com.event.interceptor;

import com.event.exception.TokenException;
import com.event.utils.JwtUtil;
import com.event.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {
	
	@Resource
	private RedisTemplate redisTemplate;
	
	/**
	 * 校验jwt
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//判断当前拦截到的是Controller的方法还是其他资源
		if (!(handler instanceof HandlerMethod)) {
			//当前拦截到的不是动态方法，直接放行
			return true;
		}
		String token = request.getHeader("Authorization");
		log.info("token令牌：{}", token);
		try {
			//校验令牌
			Map<String, Object> map = JwtUtil.parseToken(token);
			Object id = map.get("id");
			log.info("当前登录用户id：{}", id);
			String oldToken = (String) redisTemplate.opsForValue().get("token" + id);
			Map<String, Object> oldMap = JwtUtil.parseToken(oldToken);
			if (id.equals(oldMap.get("id")) && !token.equals(oldToken)) {
				response.setStatus(401);
				log.info("令牌已过期");
				throw new RuntimeException(TokenException.TOKEN_INVALID);
			}
			ThreadLocalUtil.set(id);
			//3、通过，放行
			return true;
		} catch (Exception e) {
			response.setStatus(401);
			throw new RuntimeException(e);
		}
	}
	
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
	                            Exception ex) throws Exception {
		ThreadLocalUtil.remove();
	}
}
